package org.wisteria.generator.engine.template;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wisteria.generator.engine.po.WistData;
import org.wisteria.generator.engine.util.TemplateUtils;

import java.io.*;

public class FreemarkTemplate {

    private static final Logger LOG = LoggerFactory.getLogger(FreemarkTemplate.class);

    public static Template getTemplate(String templateName) throws Exception {
        Configuration cfg = new Configuration(Configuration.getVersion());
        cfg.setSharedVariable("utils", new TemplateUtils());
        String path = FreemarkTemplate.class.getClassLoader().getResource("template").getPath();
        cfg.setDirectoryForTemplateLoading(new File(path));
        return cfg.getTemplate(templateName, "utf-8");
    }

    public static void generate(String templateName, String filePath, WistData dto) {
        Template template = null;
        try {
            template = getTemplate(templateName);
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }

        mkdirParent(filePath);

        Writer out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));
            template.process(dto, out);
        } catch (Exception e) {
            LOG.error(e.getMessage());
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    LOG.error(e.getMessage());
                }
            }
        }
    }

    private static void mkdirParent(String filePath) {
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                LOG.error(e.getMessage());
            }
        }
    }

}
